import { Body, Controller, Get, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
import { UtilityService } from 'src/shared/services/utility.service';
import { Response, Request as ExpressRequest } from 'express';
import axios, { HttpStatusCode } from 'axios';
import { JwtService } from '@nestjs/jwt';
import { ConfigurationService } from 'src/shared/services/configuration.service';
import { RedisService } from 'src/shared/services/redis.service';
import { CaptchaService } from 'src/shared/services/captcha.service';

@Controller('api/auth')
export class AuthController {
    constructor(
        private readonly utilityService: UtilityService,
        private readonly jwtService: JwtService,
        private readonly configurationService: ConfigurationService,
        private readonly redisService: RedisService,
        private readonly captchaService: CaptchaService,
    ) {

    }

    private createJwtTokens(user) {
        const access_token = this.jwtService.sign({
            id: user.id,
            order: user.order
        }, {
            secret: this.configurationService.jwtSecret,
            expiresIn: '5m'
        });
        return { access_token }
    }

    @Get('captcha')
    async getCaptcha(@Req() req: ExpressRequest, @Res() res: Response) {
        if(req.query.type === 'math'){
            const { id, data, text } = this.captchaService.generateMathCaptcha();
            console.log('id：', id, '算术验证码答案：', text);
            await this.redisService.set(id, text, 300);
            return res.json({ id, data });
        }else{
            const { id, data, text, order } = this.captchaService.generateChineseCaptcha(req.query as any);
            console.log('id：', id, '验证码：',text,'请依次点击：',order);
            await this.redisService.set(id, `${text.join('')}-${order.join('')}`, 300);
            return res.json({ id, data, order });
        }
        // res.type('svg');
        // res.send(data);
    }

    @Post('verifyCaptcha')
    async verifyCaptcha(@Res() res: Response, @Body() body) {
        let params = { id:'', order:'' }
        params = {...body}
        // console.log('验证码：',params.id,'请依次点击：',params.order);
        try {
            const result = await this.redisService.get(params.id as string);
            if(result?.indexOf('-')!== -1){
                const [TEXT, ORDER] = result?.split('-') as any
                const indices = [...ORDER].map(char => TEXT.indexOf(char)) // 查找每个字符在text中的下标
                .join(''); // 将下标拼接成字符串
                console.log('验证结果：', indices);
                if(params.order === indices){
                    const token = this.createJwtTokens({id: params.id, order: params.order})
                    return res.json({ success: true, ...token });
                }else{
                    return res.status(HttpStatusCode.Unauthorized).json({ success: false, message: '验证码错误' })
                }
            }else{
                console.log('验证结果：', result);
                if(params.order === result){
                    const token = this.createJwtTokens({id: params.id, order: params.order})
                    return res.json({ success: true, ...token });
                }else{
                    return res.status(HttpStatusCode.Unauthorized).json({ success: false, message: '验证码错误' })
                }
            }

        } catch (error) {
            return res.status(HttpStatusCode.Unauthorized).json({ success: false, message: '验证码失效' })
        }
    }

    @Post('tokenVerify')
    async tokenVerify(@Res() res: Response, @Body() body) {
        const { access_token } = body;
        // console.log('TOKEN',access_token)
        try{
            this.jwtService.verify(access_token as string, { secret: this.configurationService.jwtSecret });
            return res.json({ success: true, message: '校验成功' });
        }catch(e){
            return res.status(HttpStatusCode.Unauthorized).json({ success: false, message: 'TOKEN无效' })
        }
    }
}